class_name Gem extends Node2D

@export var travel_time : float = 1.0
@export var gravity : float = 10
@export var speed :float = 200

enum STATE{
	UNPICKED,
	FLY_TO_VALVE,
	BUBBLIZE,
	ATTACH_TO_MONSTER,
	SCORE
}
var state = STATE.UNPICKED
var valve: Valve
var monster=null
var target_pos :Vector2
var dir = Vector2(randf_range(-1,1), randf_range(0.3,1)).normalized()
var is_picked = false
var is_bubbled = false


func _ready():
	$Bubble.hide()
	$Bubble/BubbleArea.monitoring = false
	CountManager.gem_count+=1
	CountManager.gem_count_score+=1

func _physics_process(delta):
	match state:
		STATE.BUBBLIZE:
			if (global_position-target_pos).length()>10:
				global_position += dir*speed*delta
			else:
				global_position += Vector2.UP*0.5*speed*delta
				target_pos = global_position
		STATE.ATTACH_TO_MONSTER:
			global_position = monster.global_position

func move_to_valve():
	if valve:
		var tween = create_tween()
		tween.bind_node(self)
		tween.tween_property(self, "global_position", \
		valve.global_position, travel_time)
		tween.tween_callback(bubblize)



func bubblize():
	state = STATE.BUBBLIZE
	target_pos = CellManager.get_random_point()
	dir = (target_pos-self.global_position).normalized()
	$Bubble.show()
	

func change_state_to_fly_to_valve():
	state = STATE.FLY_TO_VALVE
	$Gem/PickArea.set_deferred("monitoring",false)
	$Bubble/BubbleArea.set_deferred("monitoring", true)
	valve = CellManager.valve
	move_to_valve()

func _on_pick_area_body_entered(body):
	if state == STATE.UNPICKED:
		if body is Player:
			change_state_to_fly_to_valve()
		elif body is Monster && body.state == Monster.STATE.RUN:
			state = STATE.ATTACH_TO_MONSTER
			monster = body
			monster.append_gem(self)
	
func _notification(what: int) -> void:
	if what == 1 && CountManager.state == CountManager.GAME:
		if self.state== STATE.BUBBLIZE:
			CountManager.score+=1
			CountManager.gem_count_score-=1
		elif self.state == STATE.SCORE:
			CountManager.score+=2
			CountManager.gem_count_score-=1
		CountManager.gem_count-=1
func _on_bubble_area_body_entered(body):
	if body is Player:
		$Bubble.hide()
		$Bubble/BubbleArea.set_deferred("monitoring", false)
		$Gem/PickArea.set_deferred("monitoring",true)
